package com.example.app.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.app.common.Result;
import com.example.application.RoleMenuService;
import com.example.application.UserRoleService;
import com.example.infra.po.RoleMenuPo;
import com.example.infra.po.UserRolePo;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/bind")
@RequiredArgsConstructor
public class AdminRoleBindController {

    private final UserRoleService userRoleService;
    private final RoleMenuService roleMenuService;

    @GetMapping("/user/{userId}/roles")
    public Result<List<UserRolePo>> userRoles(@PathVariable Integer userId) {
        return Result.success(userRoleService.list(new LambdaQueryWrapper<UserRolePo>().eq(UserRolePo::getUserId, userId)));
    }

    @PostMapping("/user/{userId}/roles")
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> bindUserRoles(@PathVariable Integer userId, @RequestBody IdsReq req) {
        userRoleService.remove(new LambdaQueryWrapper<UserRolePo>().eq(UserRolePo::getUserId, userId));
        if (req.getIds() != null) {
            for (Integer roleId : req.getIds()) {
                UserRolePo ur = new UserRolePo();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                userRoleService.save(ur);
            }
        }
        return Result.success(true);
    }

    @GetMapping("/role/{roleId}/menus")
    public Result<List<RoleMenuPo>> roleMenus(@PathVariable Integer roleId) {
        return Result.success(roleMenuService.list(new LambdaQueryWrapper<RoleMenuPo>().eq(RoleMenuPo::getRoleId, roleId)));
    }

    @PostMapping("/role/{roleId}/menus")
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> bindRoleMenus(@PathVariable Integer roleId, @RequestBody IdsReq req) {
        roleMenuService.remove(new LambdaQueryWrapper<RoleMenuPo>().eq(RoleMenuPo::getRoleId, roleId));
        if (req.getIds() != null) {
            for (Integer menuId : req.getIds()) {
                RoleMenuPo rm = new RoleMenuPo();
                rm.setRoleId(roleId);
                rm.setMenuId(menuId);
                roleMenuService.save(rm);
            }
        }
        return Result.success(true);
    }

    @Data
    public static class IdsReq {
        private List<Integer> ids;
    }
}


